/**
 * 定义基于pinia的store存储
 * 设置相关的store数据（token、菜单、标签等相关）
 * @author Jamen
 * @since 2022-08-11
 */
import { defineStore } from 'pinia';
import { WindowType } from '@/types/global/window';

// 创建store，defineStore调用后返回函数，调用该函数获得Store实体
const useWindowStore = defineStore({
  // 必传的参数，id值，在store中唯一
  id: 'windowStore',
  // 定义数据，返回对象和属性
  state: () => ({
    windows: [] as Array<WindowType>, // 窗口列表
    currentWindowName: '', // 当前选中的窗口name
    lastWindowName: '', // 上次选中的窗口name
  }),
  // 获取store模块的属性
  getters: {},
  // 设置store模块的属性
  actions: {
    // 添加窗口
    windowAdd(window: WindowType) {
      if (!this.windows.find((item: WindowType) => window.name == item.name)) {
        this.windows.push(window);
      }
      this.windowActive(window.name);
    },
    // 移除窗口
    windowRemove(name: string) {
      for (let i = this.windows.length - 1; i >= 0; i--) {
        if (this.windows[i].name == name) {
          this.windows.splice(i, 1);
        }
      }
      this.chooseWindow(name);
    },
    // 选中窗口
    windowActive(name: string) {
      let window: WindowType = this.windows.find(item => item.name == name);
      if (window) {
        if (this.currentWindowName != name) {
          this.lastWindowName = this.currentWindowName;
        }
        this.currentWindowName = name;
        window.minimize = false;
      }
    },
    //最小化窗口
    windowMinimize(name: string) {
      let window: WindowType = this.windows.find((item: WindowType) => item.name == name);
      window.minimize = true;
      this.chooseWindow(name);
    },
    chooseWindow(name: string) {
      let last: string = '';
      for (let i = this.windows.length - 1; i >= 0; i--) {
        let window = this.windows[i];
        if (!window.minimize) {
          if (this.lastCurrentName == window.name) {
            last = this.lastCurrentName;
          } else if (last == '' && window.name != name) {
            last = window.name;
          }
        }
      }
      this.currentWindowName = last;
    },
  },

  // 开启数据缓存  -- 需要在store/index.js中import piniaPluginPersist 插件
  persist: {
    enabled: true, // 开启持久化
    strategies: [
      {
        // key: 'token', //自定义Key，也可以去掉，使用默认值为参数id的值
        storage: localStorage, // 可以为localStorage或者sessionStorage
        // 可以通过paths指定需要持久化的值，其他没有指定的则不会持久化
        paths: [],
      },
    ],
  },
});
export default useWindowStore;
